<template>
  <div>
    <van-nav-bar title="黑马头条-登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入11位手机号"
        type="tel"
        minlength="11"
        maxlength="11"
        required
        :rules="[
          {
            required: true,
            message: '请填写合法格式手机号',
            pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
          }
        ]"
      />
      <van-field
        v-model="user.code"
        type="password"
        name="code"
        label="密码"
        placeholder="请输入6位密码"
        required
        :rules="[{ required: true, message: '请填写密码', pattern: /^\d{6}$/ }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
      <van-overlay :show="isLoading">
        <div class="wrapper" @click.stop>
          <van-loading size="24px">加载中...</van-loading>
        </div>
      </van-overlay>
    </van-form>
  </div>
</template>
<script>
import { loginAPI } from '@/api/index.js'
import Notify from '@/ui/Notify.js'
import { setToken } from '@/utils/token.js'
import { setStorage } from '@/utils/storage'
export default {
  data() {
    return {
      user: {
        // 手机号
        mobile: '13256767756',
        // 验证码（246810）
        code: '246810'
      },
      isLoading: false
    }
  },
  created() {},
  methods: {
    async onSubmit(values) {
      // const { data: res } = await loginAPI({
      //   mobile: this.user.mobile,
      //   code: this.user.code
      //    ...this.user
      // })
      this.isLoading = true
      try {
        const { data: res } = await loginAPI(this.user)
        // console.log(res)
        Notify({ type: 'success', message: '登陆成功！' })
        setToken(res.data.token)
        // 登录成功后1秒关闭
        setTimeout(() => {
          this.isLoading = false
        }, 1000)
        setStorage('refresh_token', res.data.refresh_token)
        // location.href -〉当前浏览器地址和要跳转的地址一样(不包含#后面锚点信息)-〉不会刷新网页
        // 地址改变，就会导致网页刷新
        // this.$router. push()压栈(会产生历史记录，可以回退)， this.$prouter.replace()替换(不会产生历史记录)
        // this.$roueter.replace({
        //   path: "/layout/home"
        // })
        this.$router.push('/layout/home')
      } catch (error) {
        Notify({ type: 'warning', message: '账号或密码错误' })
      }
    }
  }
}
</script>
<style lang="less" scoped></style>
